import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import { formatDate, formatNumber, parseDate } from '@/utils/fomatter';
import { EChart } from '@/components/echarts-taro3-react';
import * as echarts from "@/components/echarts-taro3-react/ec-canvas/echarts";
import './index.scss'
import dayjs from 'dayjs';
import PdsEmpty from '@/components/common/pds_empty';

interface PdsTrendChartsProps {
  netValue: Array<any>;
  indexValue: Array<any>;
  indexName: String,
  chartHidden: Boolean
}

class PdsTrendCharts extends Component<PdsTrendChartsProps, any> {

  config = {
    navigationBarTitleText: ''
  }

  state = {
    chartHidden: false
  }
  dateList = []
  lineChart: any;

  componentWillMount() { }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) {
    console.log(nextProps)

    this.configureCharts(nextProps)
  }
  componentWillUnmount() { }

  configureCharts(nextProps) {
    const { netValue, indexValue, indexName, chartHidden } = nextProps

    this.setState({ chartHidden: chartHidden })
    console.log(indexName)
    if (netValue.length < 2) {
      return
    }
    const temp_net_values = netValue.map(({ totalNet }) => totalNet);
    const temp_index_value = indexValue.map(({ indexValue }) => indexValue);

    const max_net_value = Math.max(...temp_net_values);
    const max_index_value = Math.max(...temp_index_value);
    const maxValue = Math.max(max_net_value, max_index_value) ?? 0;

    const min_net_value = Math.min(...temp_net_values);
    const min_index_value = Math.min(...temp_index_value);
    const minValue = Math.min(min_net_value, min_index_value) ?? 0;

    let option = {
      animation: false,
      tooltip: {
        trigger: 'axis',
        transitionDuration: 0,
        triggerOn: "mousemove|click",
        backgroundColor: '#ffffff',
        shadowBlur: 10,
        shadowColor: '#00000033',
        shadowOffsetY: 2,
        borderRadius: 4,
        borderWidth: 1,
        textStyle: {
          color: "#666",
          fontSize: 14,
        },
        //核心代码，处理tooltip中的数据需要在此formatter函数中做处理  小程序无效
        // formatter(params) {
        //     var relVal = params[0].name;
        //     for (var i = 0, l = params.length; i < l; i++) {
        //         console.log('tooltip数据值', params[i].value)
        //         //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
        //         relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Number(params[i].value).toFixed(4)
        //     }
        //     return relVal;
        // },
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#3C6BFF',
            formatter(data) {
              if (data.axisDimension === "x") {
                return formatDate(data.value.toString(), null, 'YYYY-MM-DD')
              } else {
                return formatNumber(data.value, 4)
              }
            }
          }
        },
      },
      grid: {
        top: 10,
        left: 66,
        right: 36,
        bottom: 24,
        borderWidth: '0'
      },
      xAxis: {
        type: 'time',
        min: 'dataMin' as string | number,
        max: 'dataMax' as string | number,
        boundaryGap: false,
        axisLine: {
          show: true,
          onZero: false
        },
        nameTextStyle: {
          overflow: 'truncate',
          ellipsis: '...',
          nameRotate: -45
        },
        axisTick: {
          show: true,    // 是否显示坐标轴刻度
        },
        splitLine: {           // 分隔线
          show: false,        // 默认显示，属性show控制显示与否
        },
        axisLabel: {
          showMinLabel: true,
          showMaxLabel: true,
          textStyle: {
            color: '#B1B9C4'
          },
          formatter: function (value) {
            const date = value.toString()
            return formatDate(date, null, 'YYYY-MM-DD')
          },
        }
      },
      yAxis: {
        type: 'value',
        min: minValue - (maxValue - minValue) / 5.0,
        max: maxValue + (maxValue - minValue) / 5.0,
        // interval: (maxValue - minValue) / 5.0,
        splitNumber: 5,
        labelPrecision: 4,
        precision: 4,
        axisLine: {
          show: false,
          onZero: false,
          lineStyle: {       // 属性lineStyle控制线条样式
            color: '#E8EBEF',

          },
        },
        axisTick: {
          show: true
        },
        splitLine: {           // 分隔线
          show: false,        // 默认显示，属性show控制显示与否
          lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
            type: 'dotted',
            opacity: 1
          }
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#B1B9C4'
          },
          formatter: function (value) {
            return formatNumber(value, 4)
          },

        }
      },
      series: [
        {
          data: netValue.map((item, index) => {
            var time = parseDate(item.initDate.toString(), 'YYYYMMDD')
            return [time, Number(item['totalNet']) ?? 0]
          }),
          type: 'line',
          name: '净值',
          symbol: 'none',
          smooth: true,
          itemStyle: {
            normal: {
              color: '#3C6BFF',
              lineStyle: {
                color: '#3C6BFF', //改变折线
                width: 2,// 0.1的线条是非常细的了
              },
            }
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [  // 渐变颜色
                {
                  offset: 1,
                  color: '#567cf233',
                  opacity: 0.2
                },
                {
                  offset: 1,
                  color: '#567cf20c',
                  opacity: 0.05
                },
              ],
              global: false,
            },
          },
        },
        {
          data: indexValue.map((item, index) => {
            var time = parseDate(item.initDate.toString(), 'YYYYMMDD')
            return [time, Number(item['indexValue']) ?? 0]
          }),
          name: indexName,
          type: 'line',
          smooth: true,
          symbol: 'none',
          itemStyle: {
            normal: {
              color: '#FF8F0B', //改变折线
              lineStyle: {
                color: '#FF8F0B',
                width: 2// 0.1的线条是非常细的了
              },
            }
          },

        }
      ]
    }

    // this.lineChart.setOption(option);

    let obj = {
      ...option,
    }

    this.lineChart.refresh(obj);
  }

  render() {

    const { netValue } = this.props
    const { chartHidden } = this.state
    console.log(chartHidden)

    var chart_hidden = false;

    if (netValue.length <= 1) {
      chart_hidden = true
    }
    let refLineChart = (node) => {
      this.lineChart = node
    }
    return (
      <View className='chart'>
        <View className={`line-chart ${(chart_hidden) ? "line-chart-hidden" : ''}`}>
          <EChart ref={refLineChart} canvasId='line1-chart' force-use-old-canvas />
        </View >
        <View className={`line-chart ${!chart_hidden ? "line-chart-hidden" : ''}`}>
          <PdsEmpty placeholderText='此区间无两个以上净值数据，无法绘制曲线'></PdsEmpty>
        </View>
      </View>

    );
  }
}
export default PdsTrendCharts;
